package com.nantai.jiafang.nantaijiafang.nt5s.Activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.hzc.imagepicker.SImagePicker;
import com.hzc.imagepicker.activity.PhotoPickerActivity;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.User;
import com.nantai.jiafang.nantaijiafang.deviceManager.preference.PreferencesUtil;
import com.nantai.jiafang.nantaijiafang.nt5s.IConstant;
import com.nantai.jiafang.nantaijiafang.utils.CompressImage;
import com.nantai.jiafang.nantaijiafang.utils.Tools;

import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class NT5SActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_CODE_AVATAR = 100;
    public static final int REQUEST_CODE_IMAGE = 101;

    private Button pickImageBtn;
    private Button searchBtn;
    private Button searchReport;
    private Button quality;
    private Button regulations;
    private Button linechart;
    private Button uperror;
    private ImageView back;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nt5s);
        initUI();
        android.support.v7.app.ActionBar actionBar=getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initUI() {
        pickImageBtn = (Button) findViewById(R.id.pick_image);
        pickImageBtn.setOnClickListener(this);
        searchBtn = (Button) findViewById(R.id.btn_search);
        searchBtn.setOnClickListener(this);
        searchReport = (Button) findViewById(R.id.btn_report);
        searchReport.setOnClickListener(this);
        quality= (Button) findViewById(R.id.btn_quality);
        quality.setOnClickListener(this);
        regulations=(Button) findViewById(R.id.btn_regulations);
        regulations.setOnClickListener(this);
        linechart=(Button)findViewById(R.id.btn_linechart);
        linechart.setOnClickListener(this);
        back=(ImageView)findViewById(R.id.iv_back);
        back.setOnClickListener(this);
        uperror=(Button)findViewById(R.id.btn_uperror);
        uperror.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pick_image:                                                       //返回
                SImagePicker
                        .from(NT5SActivity.this)
                        .maxCount(9)    //最大选择数
                        .rowCount(3)    //列数
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)  //1
                        .forResult(REQUEST_CODE_IMAGE);    //101
                break;
            case R.id.btn_search:
                Intent intent = new Intent(NT5SActivity.this, SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_report:
                Intent intent2 = new Intent(NT5SActivity.this, ReportActivity.class);
                startActivity(intent2);
                break;
            case R.id.btn_quality:
                Intent intent3 = new Intent(NT5SActivity.this, QualityActivity.class);
                startActivity(intent3);
                break;
            case R.id.btn_regulations:
                Intent intent4 = new Intent(NT5SActivity.this, RegulationsActivity.class);
                startActivity(intent4);
                break;
            case R.id.btn_linechart:
                Intent intent5 = new Intent(NT5SActivity.this, LineChartActivity.class);
                startActivity(intent5);
                break;
            case R.id.btn_uperror:
                Intent intent6 = new Intent(NT5SActivity.this, UperrorActivity.class);
                startActivity(intent6);
                break;
            case R.id.iv_back:
                finish();
                break;
        }

    }
    int n=0;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
                 ArrayList<String> pathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
               n=0;
            ArrayList<String> pathList2=new ArrayList<>();
                Tools.compressMore(this, pathList, new CompressImage() {
                    @Override
                    public void success(String filepath) {
                        /**======================*/
                        n++;
                        pathList2.add(filepath);
                        if (n==pathList.size()) {
                            RequestParams params = new RequestParams(IConstant.URL + "upload");
                            User user = PreferencesUtil.getUser(NT5SActivity.this);
                            params.addBodyParameter("MdCode", "002011");//操作对象
                            params.addBodyParameter("UserName", user.getUserName());//文件后缀名(带点)
                            List<KeyValue> list = new ArrayList<>();
                            for (int i = 0; i < pathList2.size(); i++) {
                                list.add(new KeyValue("image" + i, new File(pathList2.get(i))));
                                MultipartBody body = new MultipartBody(list, "UTF-8");
                                params.setRequestBody(body);
                            }
//                System.out.println("请求的URL：" + params.toString());
                            x.http().post(params, new Callback.CommonCallback<String>() {
                                @Override
                                public void onSuccess(String result) {
//                        System.out.println("返回结果：" + result);
                                    String results[] = result.split(":");
                                    if (results[0].equals("1")) {
                                        Toast.makeText(NT5SActivity.this, "上传成功", Toast.LENGTH_LONG).show();
                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {

                                }

                                @Override
                                public void onCancelled(CancelledException cex) {

                                }

                                @Override
                                public void onFinished() {
                                    for (int i = 0; i < pathList2.size(); i++) {
                                        if (new File(pathList2.get(i)).exists()) {
                                            new File(pathList2.get(i)).delete();
                                        }
                                    }
                                }
                            });
                        }
                    }
                });
       }
    }
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }
}
